﻿using UnityEngine;
using System.Collections;
/// <summary>
/// -Adding this component to an Enemy will give it the ability to shoot Bullets(prefab) at the player, 
/// requires Ai component.
/// </summary>
public class AiShoot : MonoBehaviour {

    public GameObject Bullet;
    public float RoF;
    public float NextFire;

    Ai Bot;

    int LM;

    void Start() {
        Bot = GetComponent<Ai>();
        LM =1 | 1 << LayerMask.NameToLayer("Player");
    }
    
    void Update() {
        if(Bot.enabled == false || Bot.Target == null ) return;
        if((NextFire -= Time.deltaTime) < 0.0f) {
            NextFire += RoF * 0.25f;
            if((transform.position - Bot.Target.transform.position).sqrMagnitude < 15.0f * 15.0f) {

                var hit = Physics2D.Raycast(transform.position, (Bot.Target.transform.position - transform.position).normalized, 15.0f, LM);        

                if(hit && hit.collider == Bot.Target.collider2D) {

                    var b = Instantiate(Bullet, transform.position, Quaternion.LookRotation( Vector3.forward, Bot.Target.transform.position - transform.position+(Vector3) (Random.insideUnitCircle*0.3f *Mathf.Sqrt( (Bot.Target.transform.position - transform.position).magnitude))) ) as GameObject;

                    b.rigidbody2D.velocity = b.transform.up * 6.0f;
                  //  b.rigidbody2D.angularVelocity = Random.Range(-600, 600);

                    //StartCoroutine(delayedDestroy(5.0f, gameObject));

                    NextFire += RoF * 0.75f * Random.Range(1.0f, 1.3f);

                    Bot.Slow = RoF*0.7f;
                } 
            }
        }

    }

}
